package com.demo.app.common.auth;

import com.demo.app.common.Result;
import com.demo.app.constant.AuthConstant;
import com.demo.app.exception.PermissionException;
import com.demo.app.util.RedisUtil;
import com.demo.app.util.ResponseJsonUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 主权限拦截器
 * </p>
 *
 * @author zhangxt
 * @date 2023/10/31
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    PermissionAuthenticator authenticator;

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object Handle) {
        Result result = new Result();
        // 获取请求传来的token
        String token = request.getHeader(AuthConstant.AUTH_HEADER);
        // token 解析
        Jws<Claims> claims;
        try {
            claims = authenticator.checkToken(token);
            // 注销检查
            authenticator.checkLogout(claims);
            return true;
        } catch (PermissionException e) {
            response.setStatus(e.getHttpStatus());
            result.setMsg(e.getMessage());
            ResponseJsonUtil.writeJSON(response, result);
            return false;
        }
    }
}
